<template>
  <div class="reminder-management">
    <!-- 页面标题 -->
    <h2 class="page-title">催缴管理</h2>

    <!-- 搜索筛选区域 -->
    <div class="search-filters">
      <div class="filter-row">
        <!-- 户主姓名搜索 -->
        <div>
          <span class="search-item">户主姓名</span>
          <input
              v-model="searchForm.name"
              type="text"
              placeholder="请输入户主姓名"
              class="input-field"
          />
        </div>

        <!-- 缴费状态筛选 -->
        <div>
          <span class="search-item">缴费状态</span>
          <select v-model="searchForm.paymentStatus" class="select-field">
            <option value="">全部</option>
            <option value="临期">临期</option>
            <option value="逾期">逾期</option>
          </select>
        </div>

        <!-- 催缴状态筛选 -->
        <div>
          <span class="search-item">催缴状态</span>
          <select v-model="searchForm.reminderStatus" class="select-field">
            <option value="">全部</option>
            <option value="未催缴">未催缴</option>
            <option value="三天内未催缴">三天内未催缴</option>
            <option value="七天内未催缴">七天内未催缴</option>
          </select>
        </div>

        <!-- 催缴次数筛选 -->
        <div>
          <span class="search-item">催缴次数</span>
          <input
              v-model.number="searchForm.reminderCount"
              type="number"
              min="0"
              placeholder="请输入催缴次数"
              class="input-field"
          />
        </div>

        <button @click="handleSearch" class="btn-primary">
          <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPnga03cd43e27317f20428660e14317e35a64a3d907d88f824770f063b2f9fd5f10" alt="搜索" class="btn-icon" />
          搜索
        </button>
        <button @click="handleReset" class="btn-secondary">
          <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPngd1ee69767e02bb56b7c745624d059b292108792e966600668227ff5d22467bbe" alt="重置" class="btn-icon" />
          重置
        </button>
      </div>
    </div>

    <!-- 分割线 -->
    <div class="divider"></div>

    <!-- 操作按钮组 -->
    <div class="operation-buttons">
      <button @click="handleBatchReminder" class="btn-add">
        <img src="https://lanhu-oss-proxy.lanhuapp.com/SketchPng7e588fa8b8650f5efd6ef1233ed984dd6881ff2d70f829a9cd26b4482d233394" alt="催缴" class="btn-icon" />
        催缴
      </button>

      <!-- 批量操作按钮 -->
      <button
          v-if="selectedRecords.length > 0"
          @click="handleSelectedReminder"
          class="btn-batch-delete"
      >
        批量催缴 ({{ selectedRecords.length }})
      </button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
        <tr class="table-header">
          <th>
            <input
                type="checkbox"
                @change="handleSelectAll"
                :checked="isAllSelected"
                class="checkbox"
            />
          </th>
          <th>序号</th>
          <th>户主姓名</th>
          <th>联系电话</th>
          <th>到期时间</th>
          <th>剩余天数</th>
          <th>催缴次数</th>
          <th>上次催缴时间</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <template v-for="(record, index) in paginatedRecords" :key="record.id">
          <tr class="table-row">
            <td>
              <input
                  type="checkbox"
                  :value="record.id"
                  v-model="selectedRecords"
                  class="checkbox"
              />
            </td>
            <td>{{ (pagination.currentPage - 1) * pagination.pageSize + index + 1 }}</td>
            <td>{{ record.tenantName }}</td>
            <td>{{ record.phone }}</td>
            <td>{{ record.dueDate }}</td>
            <td :class="getDaysLeftClass(record.daysLeft)">
              {{ record.daysLeft > 0 ? `剩余${record.daysLeft}天` : `逾期${Math.abs(record.daysLeft)}天` }}
            </td>
            <td>{{ record.reminderCount }}</td>
            <td>{{ record.lastReminderDate || '未催缴' }}</td>
            <td class="action-buttons">
              <button @click="handleSingleReminder(record)" class="action-btn" title="催缴">
                催缴
              </button>
            </td>
          </tr>
        </template>
        </tbody>
      </table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination">
      <span class="pagination-info">共 {{ pagination.totalPages }} 页</span>
      <button @click="goToPrevPage" :disabled="pagination.currentPage === 1" class="pagination-btn">上一页</button>
      <button
          v-for="page in visiblePages"
          :key="page"
          @click="goToPage(page)"
          :class="['pagination-btn', { 'active': page === pagination.currentPage }]"
      >
        {{ page }}
      </button>
      <button @click="goToNextPage" :disabled="pagination.currentPage === pagination.totalPages" class="pagination-btn">下一页</button>
      <span class="pagination-goto">前往</span>
      <input v-model.number="gotoPage" @keyup.enter="handleGotoPage" class="goto-input" />
      <span>页</span>
    </div>

    <!-- 催缴确认弹窗 -->
    <div v-if="showReminderModal" class="modal-overlay" @click="closeReminderModal">
      <div class="modal-content reminder-modal" @click.stop>
        <div class="modal-header">
          <h3>催缴确认</h3>
          <button @click="closeReminderModal" class="close-btn">×</button>
        </div>
        <div class="modal-body">
          <div v-if="reminderType === 'all'">
            <p>确定要对当前查询结果的 {{ filteredRecords.length }} 条记录进行催缴吗？</p>
          </div>
          <div v-else-if="reminderType === 'selected'">
            <p>确定要对选中的 {{ selectedRecords.length }} 条记录进行催缴吗？</p>
          </div>
          <div v-else-if="reminderType === 'single'">
            <p>确定要对住户 "{{ reminderTarget.tenantName }}" 进行催缴吗？</p>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closeReminderModal" class="btn-cancel">取消</button>
          <button @click="confirmReminder" class="btn-save">确定</button>
        </div>
      </div>
    </div>

    <!-- 催缴成功提示 -->
    <div v-if="showSuccessMessage" class="message-overlay">
      <div class="message-content">
        <p>催缴成功！</p>
        <button @click="closeSuccessMessage" class="btn-save">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 响应式数据
const searchForm = ref({
  name: '',
  paymentStatus: '',
  reminderStatus: '',
  reminderCount: ''
})

// 模拟缴费记录数据
const paymentRecords = ref([
  {
    id: 1,
    tenantName: '张三',
    phone: '13800138001',
    dueDate: '2024-06-30',
    daysLeft: 5,
    reminderCount: 0,
    lastReminderDate: null
  },
  {
    id: 2,
    tenantName: '李四',
    phone: '13800138002',
    dueDate: '2024-06-25',
    daysLeft: -2,
    reminderCount: 1,
    lastReminderDate: '2024-06-24'
  },
  {
    id: 3,
    tenantName: '王五',
    phone: '13800138003',
    dueDate: '2024-07-05',
    daysLeft: 10,
    reminderCount: 0,
    lastReminderDate: null
  },
  {
    id: 4,
    tenantName: '赵六',
    phone: '13800138004',
    dueDate: '2024-06-28',
    daysLeft: 2,
    reminderCount: 0,
    lastReminderDate: null
  },
  {
    id: 5,
    tenantName: '钱七',
    phone: '13800138005',
    dueDate: '2024-06-20',
    daysLeft: -5,
    reminderCount: 2,
    lastReminderDate: '2024-06-18'
  },
  {
    id: 6,
    tenantName: '孙八',
    phone: '13800138006',
    dueDate: '2024-07-01',
    daysLeft: 6,
    reminderCount: 0,
    lastReminderDate: null
  },
  {
    id: 7,
    tenantName: '周九',
    phone: '13800138007',
    dueDate: '2024-06-15',
    daysLeft: -10,
    reminderCount: 0,
    lastReminderDate: null
  },
  {
    id: 8,
    tenantName: '吴十',
    phone: '13800138008',
    dueDate: '2024-06-29',
    daysLeft: 3,
    reminderCount: 1,
    lastReminderDate: '2024-06-26'
  },
  {
    id: 9,
    tenantName: '郑十一',
    phone: '13800138009',
    dueDate: '2024-07-03',
    daysLeft: 8,
    reminderCount: 0,
    lastReminderDate: null
  },
  {
    id: 10,
    tenantName: '王十二',
    phone: '13800138010',
    dueDate: '2024-06-22',
    daysLeft: -3,
    reminderCount: 1,
    lastReminderDate: '2024-06-20'
  }
])

const filteredRecords = ref([])

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  totalPages: 1,
  total: 0
})

const selectedRecords = ref([])
const gotoPage = ref('')

// 弹窗相关
const showReminderModal = ref(false)
const reminderType = ref('') // 'all', 'selected', 'single'
const reminderTarget = ref({})

const showSuccessMessage = ref(false)

// 计算属性
const paginatedRecords = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return filteredRecords.value.slice(start, end)
})

const visiblePages = computed(() => {
  const current = pagination.value.currentPage
  const total = pagination.value.totalPages
  const pages = []

  for (let i = Math.max(1, current - 2); i <= Math.min(total, current + 2); i++) {
    pages.push(i)
  }

  return pages
})

const isAllSelected = computed(() => {
  return paginatedRecords.value.length > 0 &&
      paginatedRecords.value.every(record => selectedRecords.value.includes(record.id))
})

// 方法
const updatePagination = () => {
  pagination.value.total = filteredRecords.value.length
  pagination.value.totalPages = Math.ceil(filteredRecords.value.length / pagination.value.pageSize)
  if (pagination.value.currentPage > pagination.value.totalPages) {
    pagination.value.currentPage = 1
  }
}

const getDaysLeftClass = (daysLeft) => {
  if (daysLeft > 0 && daysLeft <= 7) {
    // 临期（黄色背景）
    return 'days-warning-bg'
  } else if (daysLeft <= 0 && daysLeft >= -7) {
    // 逾期0至7天（红色背景）
    return 'days-overdue-bg'
  } else if (daysLeft < -7) {
    // 逾期超过7天（深红色背景）
    return 'days-overdue-severe-bg'
  }
  return ''
}

const handleSearch = () => {
  filteredRecords.value = paymentRecords.value.filter(record => {
    // 只显示剩余天数小于等于7天或逾期的记录
    if (record.daysLeft > 7) {
      return false
    }

    return (
        // 户主姓名模糊匹配
        (!searchForm.value.name || record.tenantName.includes(searchForm.value.name)) &&

        // 缴费状态筛选
        (!searchForm.value.paymentStatus ||
         (searchForm.value.paymentStatus === '临期' && record.daysLeft >= 0 && record.daysLeft <= 7) ||
         (searchForm.value.paymentStatus === '逾期' && record.daysLeft < 0)) &&

        // 催缴状态筛选
        (!searchForm.value.reminderStatus ||
         (searchForm.value.reminderStatus === '未催缴' && record.reminderCount === 0) ||
         (searchForm.value.reminderStatus === '三天内未催缴' &&
          record.reminderCount === 0 && record.daysLeft >= 0 && record.daysLeft <= 3) ||
         (searchForm.value.reminderStatus === '七天内未催缴' &&
          record.reminderCount === 0 && record.daysLeft >= 0 && record.daysLeft <= 7)) &&

        // 催缴次数筛选
        (searchForm.value.reminderCount === '' || record.reminderCount === searchForm.value.reminderCount)
    )
  })
  pagination.value.currentPage = 1
  selectedRecords.value = []
  updatePagination()
}

const handleReset = () => {
  searchForm.value = {
    name: '',
    paymentStatus: '',
    reminderStatus: '',
    reminderCount: ''
  }
  handleSearch()
}

const handleSelectAll = (event) => {
  if (event.target.checked) {
    selectedRecords.value = paginatedRecords.value.map(record => record.id)
  } else {
    selectedRecords.value = []
  }
}

const handleBatchReminder = () => {
  reminderType.value = 'all'
  showReminderModal.value = true
}

const handleSelectedReminder = () => {
  if (selectedRecords.value.length === 0) return
  reminderType.value = 'selected'
  showReminderModal.value = true
}

const handleSingleReminder = (record) => {
  reminderType.value = 'single'
  reminderTarget.value = record
  showReminderModal.value = true
}

const confirmReminder = () => {
  const now = new Date().toLocaleString()

  if (reminderType.value === 'all') {
    // 对当前查询结果全部催缴
    filteredRecords.value.forEach(record => {
      record.reminderCount += 1
      record.lastReminderDate = now
    })
  } else if (reminderType.value === 'selected') {
    // 对选中记录催缴
    paymentRecords.value.forEach(record => {
      if (selectedRecords.value.includes(record.id)) {
        record.reminderCount += 1
        record.lastReminderDate = now
      }
    })
    filteredRecords.value.forEach(record => {
      if (selectedRecords.value.includes(record.id)) {
        record.reminderCount += 1
        record.lastReminderDate = now
      }
    })
    selectedRecords.value = []
  } else if (reminderType.value === 'single') {
    // 对单条记录催缴
    paymentRecords.value.forEach(record => {
      if (record.id === reminderTarget.value.id) {
        record.reminderCount += 1
        record.lastReminderDate = now
      }
    })
    filteredRecords.value.forEach(record => {
      if (record.id === reminderTarget.value.id) {
        record.reminderCount += 1
        record.lastReminderDate = now
      }
    })
  }

  closeReminderModal()
  showSuccessMessage.value = true
  handleSearch() // 重新筛选以更新状态
}

const closeReminderModal = () => {
  showReminderModal.value = false
  reminderType.value = ''
  reminderTarget.value = {}
}

const closeSuccessMessage = () => {
  showSuccessMessage.value = false
}

const goToPage = (page) => {
  pagination.value.currentPage = page
  selectedRecords.value = []
}

const goToPrevPage = () => {
  if (pagination.value.currentPage > 1) {
    pagination.value.currentPage--
    selectedRecords.value = []
  }
}

const goToNextPage = () => {
  if (pagination.value.currentPage < pagination.value.totalPages) {
    pagination.value.currentPage++
    selectedRecords.value = []
  }
}

const handleGotoPage = () => {
  const page = parseInt(gotoPage.value)
  if (page >= 1 && page <= pagination.value.totalPages) {
    pagination.value.currentPage = page
    gotoPage.value = ''
    selectedRecords.value = []
  }
}

// 生命周期
onMounted(() => {
  handleSearch()
})
</script>

<style scoped>
/* 基础布局样式 */
.reminder-management {
  width: 100%;
  background-color: rgba(255, 255, 255, 1);
  padding: 30px 30px;
  box-sizing: border-box;
  overflow: hidden;
  border-radius: 0 15px 15px 15px;
}

/* 页面标题 */
.page-title {
  color: rgba(231, 59, 69, 1);
  font-size: 18px;
  font-family: PingFangSC-Medium;
  font-weight: 500;
  margin: 0 0 20px 0;
  line-height: 25px;
}

/* 搜索筛选区域 */
.search-filters {
  margin-bottom: 6px;
}

.search-item {
  display: block;
  margin-bottom: 5px;
}

.filter-row {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
  width: 1527px;
  height: 32px;
}

/* 统一的输入框和选择框样式 */
.input-field, .select-field {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  height: 32px;
  border: 1px solid rgba(216, 216, 216, 1);
  width: 180px;
  padding: 6px 10px;
  font-size: 14px;
  color: rgba(153, 153, 153, 1);
  box-sizing: border-box;
  line-height: 20px;
}

.input-field:focus, .select-field:focus {
  outline: none;
  border-color: rgba(231, 59, 69, 1);
  color: rgba(0, 0, 0, 1);
}

.input-field::placeholder {
  color: rgba(153, 153, 153, 1);
}

/* 统一的按钮样式 */
.btn-primary {
  background-color: rgba(231, 59, 69, 1);
  border-radius: 4px;
  width: 80px;
  height: 32px;
  border: none;
  color: rgba(255, 255, 255, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  cursor: pointer;
  margin-left: 20px;
}

.btn-secondary {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  width: 80px;
  height: 32px;
  border: 1px solid rgba(151, 151, 151, 1);
  color: rgba(135, 136, 138, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  cursor: pointer;
}

.btn-add {
  background-color: rgba(252, 235, 236, 1);
  border-radius: 19px;
  width: 80px;
  height: 32px;
  border: none;
  color: rgba(231, 59, 69, 1);
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-add:hover {
  background-color: rgba(248, 220, 222, 1);
}

.btn-batch-delete {
  background-color: rgba(255, 77, 79, 1);
  border-radius: 19px;
  height: 32px;
  padding: 0 16px;
  border: none;
  color: rgba(255, 255, 255, 1);
  font-size: 14px;
  cursor: pointer;
  margin-left: 20px;
}

.btn-batch-delete:hover {
  background-color: rgba(235, 57, 59, 1);
}

.btn-icon {
  width: 13px;
  height: 13px;
}

/* 分割线 */
.divider {
  width: 1533px;
  height: 1px;
  background-color: rgba(237, 239, 244, 1);
  margin: 50px 0 0 0;
}

/* 操作按钮组样式 */
.operation-buttons {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  margin: 20px 0;
}

/* 表格样式 */
.table-container {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 4px;
  border: 1px solid rgba(237, 239, 244, 1);
  width: 100%;
  height: 610px;
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.table-header {
  background-color: rgba(249, 248, 252, 1);
  height: 60px;
  border-radius: 4px;
  border: 1px solid rgba(237, 239, 244, 1);
}

.table-header th {
  color: rgba(0, 0, 0, 1);
  font-size: 16px;
  font-weight: normal;
  text-align: left;
  padding: 13px 21px;
  line-height: 20px;
}

.table-row {
  background-color: rgba(255, 255, 255, 1);
  height: 55px;
  border: 1px solid rgba(237, 239, 244, 1);
}

.table-row td {
  color: rgba(102, 102, 102, 1);
  font-size: 16px;
  font-weight: normal;
  padding: 10px 21px;
  line-height: 20px;
  white-space: nowrap;
}

/* 复选框样式 */
.checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 20px;
  align-items: center;
}

.action-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgba(231, 59, 69, 1);
  text-decoration: underline;
}

/* 剩余天数样式 */
.days-warning-bg {
  background-color: #fffbe6;
  color: #fa8c16;
  font-weight: bold;
  padding: 4px 8px;
  border-radius: 4px;
}

.days-overdue-bg {
  background-color: #fff1f0;
  color: #ff4d4f;
  font-weight: bold;
  padding: 4px 8px;
  border-radius: 4px;
}

.days-overdue-severe-bg {
  background-color: #ffccc7;
  color: #cf1322;
  font-weight: bold;
  padding: 4px 8px;
  border-radius: 4px;
}

/* 分页样式 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.pagination-info {
  color: rgba(102, 102, 102, 1);
  font-size: 14px;
  line-height: 20px;
}

.pagination-btn {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 14px;
  color: rgba(102, 102, 102, 1);
  cursor: pointer;
  min-width: 32px;
  height: 32px;
  line-height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-btn:hover:not(:disabled) {
  background-color: rgba(249, 248, 252, 1);
}

.pagination-btn.active {
  background-color: rgba(231, 59, 69, 1);
  color: white;
  border-color: rgba(231, 59, 69, 1);
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-goto {
  color: rgba(102, 102, 102, 1);
  font-size: 14px;
  line-height: 20px;
  margin-left: 20px;
}

.goto-input {
  width: 50px;
  height: 32px;
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 6px;
  font-size: 14px;
  text-align: center;
  line-height: 20px;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 800px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.reminder-modal {
  width: 400px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid rgba(237, 239, 244, 1);
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: rgba(231, 59, 69, 1);
  font-weight: 500;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: rgba(102, 102, 102, 1);
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: rgba(231, 59, 69, 1);
}

.modal-body {
  padding: 20px;
}

.modal-body p {
  font-size: 16px;
  color: rgba(102, 102, 102, 1);
  line-height: 1.5;
  margin: 0;
  text-align: center;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid rgba(237, 239, 244, 1);
}

.btn-cancel {
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(216, 216, 216, 1);
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  color: rgba(102, 102, 102, 1);
  cursor: pointer;
  line-height: 20px;
}

.btn-save {
  background-color: rgba(231, 59, 69, 1);
  border: none;
  border-radius: 4px;
  padding: 8px 20px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  line-height: 20px;
}

.btn-cancel:hover {
  background-color: rgba(249, 248, 252, 1);
}

.btn-save:hover {
  background-color: rgba(207, 53, 63, 1);
}

/* 成功提示样式 */
.message-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
}

.message-content {
  background-color: white;
  border-radius: 8px;
  padding: 30px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.message-content p {
  font-size: 18px;
  color: rgba(231, 59, 69, 1);
  margin: 0 0 20px 0;
}
</style>
